package com.pbdatabase.core.main;

import org.apache.log4j.Logger;

import java.io.*;
import java.util.UUID;

public class ProtoProcessor {
	private static Logger _logger = Logger.getLogger(ProtoProcessor.class);

	public static void saveProto(String protoName, String protoContent) {
		if (null == protoName || null == protoContent || protoName.length() == 0 || protoContent.length() == 0) {
			throw new IllegalArgumentException("protoName and protoContent can't be empty");
		}
		String protoLocation = PropertyManager.getInstance().getProtoLocation();
		if (!protoLocation.substring(protoLocation.length() - 1).equals("/")) {
			protoLocation += "/";
		}
		String protoFile = protoLocation + protoName;
		PrintWriter out = null;
		try {
			out = new PrintWriter(protoFile);
			out.println(protoContent);
			_logger.info("Saving proto to file: " + protoFile);
			_logger.debug("Proto being saved: " + protoContent);
		} catch (IOException ex) {
			_logger.error("Issue with saving proto file", ex);
		} finally {
			if (null != out)
				out.close();
		}
	}

	public static String saveMessage(String protoName, Object protoMessage) {
		if (null == protoName || null == protoMessage || protoName.length() == 0) {
			throw new IllegalArgumentException("protoName and protoMessage can't be empty");
		}
		String messageLocation = PropertyManager.getInstance().getMessageLocation();
		if (!messageLocation.substring(messageLocation.length() - 1).equals("/")) {
			messageLocation += "/";
		}
		String fileName = protoName + UUID.randomUUID().toString();
		String messagefile = messageLocation + fileName;
		BufferedWriter bufferedWriter = null;
		try {
			bufferedWriter = new BufferedWriter(new FileWriter(messagefile));
			_logger.info("Saving message to file: " + messagefile);
			return fileName;
		} catch (IOException ex) {
			_logger.error("Issue with saving proto file", ex);
			return "";
		} finally {
			if (null != bufferedWriter) {
				try {
					bufferedWriter.close();
				} catch (Exception e) { }
			}
		}
	}


	public static void generateCodeFromProto(String protoName) {
		if (null == protoName || protoName.length() == 0) {
			throw new IllegalArgumentException("protoName can't be empty");
		}

		// Get various paths
		String protoLocation = PropertyManager.getInstance().getProtoLocation();
		String protoFile = protoLocation + protoName;
		String generatedLocation = PropertyManager.getInstance().getGeneratedLocation();

		try {
			// Prepare command
			Runtime runtime = Runtime.getRuntime();
			String command = "protoc -I=" + protoLocation +
				" --java_out=" + generatedLocation + " " +
				protoFile;
			_logger.info("Going to execute: " + command);

			// Execute command
			Process process = runtime.exec(command);

			// Get details
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				_logger.info(line);
			}

			// Exit value
			int exitValue = process.waitFor();
			_logger.info("Process finished with code: " + exitValue);

			// TODO: Make decision based on exit value
		}
		catch (Exception ex) {
			_logger.error("Issue with processing proto file", ex);
		}
	}
}
